package cn.itcast.nems.studentrecord.web.controller.b;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.bean.Page;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.PageQueryModel;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.journal.dto.*;
import cn.itcast.nems.journal.enumeration.JournalFinalErrorBodyEnum;
import cn.itcast.nems.journal.service.JournalFinalLineService;
import cn.itcast.nems.journal.service.JournalFinalService;
import cn.itcast.nems.manager.util.CustomBeanUtil;
import cn.itcast.nems.manager.util.RequestToEntityConverter;
import cn.itcast.nems.studentrecord.bo.JournalClazzModel;
import cn.itcast.nems.studentrecord.dao.condition.ApprovalType;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalFinalDO;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalFinalLineDO;
import cn.itcast.nems.studentrecord.web.vo.form.JournalFinalEditVO;
import cn.itcast.nems.studentrecord.web.vo.response.JournalFinalLinePageVO;
import cn.itcast.nems.studentrecord.web.vo.response.JournalFinalPageVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 结课凭单-头 前端控制器
 * </p>
 *
 * @author CodeGenerator
 * @since 2024-01-04
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/b/journal/final")
public class JournalFinalController {
    private final JournalFinalService journalFinalService;
    /**
     * <p>
     * 分页查询
     * </p>
     *
     * @param approvalType 审批类型
     * @param pageNumber 页码
     * @param pageSize 每页显示最大条目
     * @author zhouwei
     * @since 2024/1/11 11:05 AM
     **/
    @GetMapping(value = "/list/{approval_type}")
    public ResponseEntity<Page<JournalFinalPageVO>> list(HttpServletRequest request,
                                                         @PathVariable("approval_type") String approvalType,
                                                         @RequestParam(value = "page_number", required = false) Integer pageNumber,
                                                         @RequestParam(value = "page_size", required = false) Integer pageSize) {
        Assert.notNull(approvalType , BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY ,"审批类型"));
        JournalFinalModel queryVO = (JournalFinalModel) RequestToEntityConverter.convert(request, JournalFinalModel.class);
        queryVO.setApprovalType(ApprovalType.valueOf(approvalType.toUpperCase()));
        PageQueryModel<JournalFinalModel> queryModel = new PageQueryModel<>(pageNumber, pageSize, queryVO);
        queryModel.convert();
        IPage<JournalFinalDO> pageData = journalFinalService.pageList(queryModel);
        List<JournalFinalPageVO> list = Objects.isNull(pageData) ||  CollectionUtil.isEmpty(pageData.getRecords()) ?
                null :
                pageData.getRecords().stream().map(this::transferToJournalFinalPageVO).toList();
        return ResponseEntity.ok().body(
                Page.of(
                        queryModel.getPageNumber(),
                        queryModel.getPageSize(),
                        Objects.nonNull(pageData)  ?Long.valueOf(pageData.getTotal()).intValue():0,
                        list
                )
        );
    }

    private JournalFinalPageVO  transferToJournalFinalPageVO(JournalFinalDO  journalFinalDO)  {
        JournalFinalPageVO journalFinalPageVO =  CustomBeanUtil.copyProperties(journalFinalDO , new JournalFinalPageVO());
        return  journalFinalPageVO ;
    }

    /**
     * 查询分页条件班级名称
     *
     * @return 班级列表(包含字段：班级ID、班级名称)
     */
    @GetMapping("/clazz/{approval_type}")
    public ResponseEntity<Page<JournalClazzDTO>> findClazzList4PageSearch(HttpServletRequest request,
                                                                          @PathVariable("approval_type") String approvalType,
                                                                          @RequestParam(value = "page_number", required = false) Integer pageNumber,
                                                                          @RequestParam(value = "page_size", required = false) Integer pageSize)
    {
        Assert.notNull(approvalType , BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY ,"审批类型"));
        JournalClazzModel queryVO = (JournalClazzModel) RequestToEntityConverter.convert(request, JournalClazzModel.class);
        queryVO.setApprovalType(ApprovalType.valueOf(approvalType.toUpperCase()));
        PageQueryModel<JournalClazzModel> queryModel = new PageQueryModel<>(pageNumber, pageSize, queryVO);
        queryModel.convert();
        Page<JournalClazzDTO> pageData = journalFinalService.findClazzList4PageSearch(queryModel);
        return ResponseEntity.ok(pageData);
    }
    
    /**
     * 
     * 功能描述：获取单个结课凭单（含凭单行）
     *
     * @param id 结课凭单ID
     * @return 结课凭单详情（含凭单行）
     * 
     * @author 刘曙
     *
     * @since 2024年1月4日
     *
     * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    @GetMapping(value = "/{id}")
    public ResponseEntity<JournalFinalDTO> getById(@PathVariable("id") String id) {
        JournalFinalDTO jf = journalFinalService.getById(id);
        return new ResponseEntity<>(jf, HttpStatus.OK);
    }


    /**
     * 
     * 功能描述：创建结课凭单
     *
     * @param params 结课凭单相关参数
     * @return 创建成功文案
     * 
     * @author 刘曙
     *
     * @since 2024年1月4日
     *
     * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    @PostMapping
    public ResponseEntity<String> create(@Validated @RequestBody JournalFinalEditVO params) {
        Assert.isNull(params.getId() ,BizExceptionProducer.produce(JournalFinalErrorBodyEnum.JOURNAL_ID_NOT_NULL ));
        JournalFinalEditDTO jfeDTO = new JournalFinalEditDTO();
        BeanUtils.copyProperties(params, jfeDTO);
        return  ResponseEntity.ok().body(journalFinalService.save(jfeDTO));
    }
    /**
     * <p>
     * 根据凭单ID 刷新行数据
     * </p>
     *
     * @author zhouwei
     * @since 2024/1/12 4:09 PM
     **/
    @GetMapping("/refresh/{journal_id}")
    public ResponseEntity<Boolean> refresh(@PathVariable("journal_id") String journalId) {
        Assert.notNull(journalId , BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY ,"凭单ID")) ;
        journalFinalService.refreshLines(journalId) ;
        return ResponseEntity.ok().body(true) ;
    }
    
    /**
     * 
     * 功能描述：更新结课凭单
     *
     * @param params 需要更新的凭单数据
     * @return 更新成功文案
     * 
     * @author 刘曙
     *
     * @since 2024年1月4日
     *
     * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    @PutMapping
    public ResponseEntity<List<JournalFinalClazzLockRecordDTO>> update(@RequestBody JournalFinalEditVO params) {
        this.validateUpdateParam(params);
        JournalFinalEditDTO journalFinalEditDTO =  CustomBeanUtil.copyProperties(params, new JournalFinalEditDTO());
        List<JournalFinalClazzLockRecordDTO> list= journalFinalService.update( journalFinalEditDTO);
        return  ResponseEntity.ok().body(list);
    }

    private void validateUpdateParam(JournalFinalEditVO params) {
        Assert.notNull(params ,BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY , "结课表单参数")) ;
        Assert.notNull(params.getId() ,BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY , "结课凭单ID")) ;
        Assert.notBlank(params.getState() ,BizExceptionProducer.produce(NemsErrorBodyEnum.PARAM_EMPTY , "结课凭单ID")) ;

    }

    /**
     * <p>
     * 分特列表 - 提交审批
     * </p>
     *
     * @param id 凭单ID
     * @author zhouwei
     * @since 2024/1/13 3:05 PM
     **/
    @PutMapping(value = "/flow/{id}")
    public ResponseEntity<List<JournalFinalClazzLockRecordDTO>> flow(@PathVariable("id") String id) {
        List<JournalFinalClazzLockRecordDTO> list = journalFinalService.flow(id);
        return ResponseEntity.ok().body(list);
    }

    
    /**
     * 
     * 功能描述：删除结课凭单
     *
     * @param id 结课凭单ID
     * @return 删除成功文案
     * 
     * @author 刘曙
     *
     * @since 2024年1月4日
     *
     * @update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
     */
    @DeleteMapping(value = "/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") String id) {
        journalFinalService.removeById(id);
        return new ResponseEntity<>("结课凭单删除成功！", HttpStatus.OK);
    }
    /**
     * <p>
     * 根据班ID查询开班时间、预计结课时间、在籍人数和在途人数及在途列表
     * </p>
     *
     * @author zhouwei
     * @since 2024/1/12 9:16 AM
     **/
    @GetMapping("/clazz_info/{clazz_id}")
    public ResponseEntity<?> getClassInfo(@PathVariable("clazz_id") Integer clazzId) {
        JournalFinalClazzDTO clazzDTO    =journalFinalService.getClazzInfoByClazzId(clazzId);
        return  ResponseEntity.ok().body(clazzDTO) ;
    }
}
